package org.jsola.hr.web;

import org.apache.commons.lang3.StringUtils;
import org.jsola.admin.query.HeaderFieldsQuery;
import org.jsola.admin.vo.HeaderFieldsVO;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.FormGroupAddDTO;
import org.jsola.hr.dto.FormGroupBatchDTO;
import org.jsola.hr.dto.FormGroupUpdateDTO;
import org.jsola.hr.query.FormGroupQuery;
import org.jsola.hr.query.FormQuery;
import org.jsola.hr.service.IFormGroupService;
import org.jsola.hr.vo.FormGroupListVO;
import org.jsola.hr.vo.FormGroupVO;
import org.jsola.hr.vo.FormHeaderVO;
import org.jsola.hr.vo.FormVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import javax.validation.Valid;


/**
 * 表单字段分组
 *
 * @author zhr
 */
@RestController("hrFormGroupController")
@RequestMapping(HrConstants.API_PATH + "/v1/formGroups")
public class FormGroupController implements IFormGroupControllerAPI {

    @Autowired
    private IFormGroupService formGroupService;

    @Override
    @PostMapping
    public Result<FormGroupVO> save(@Valid @RequestBody FormGroupAddDTO formGroupAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增表单字段分组权限校验

        return Result.success(
                formGroupService.save(formGroupAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody FormGroupUpdateDTO formGroupUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改表单字段分组权限校验

        int count = formGroupService.update(formGroupUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @PostMapping(value = "/batch")
    public Result batch(@Valid @RequestBody FormGroupBatchDTO formGroupBatchDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量操作权限校验

        // 批量操作，注意校验，有越权风险
        // 新增
        List<FormGroupAddDTO> formGroupAddDTOList = formGroupBatchDTO.getFormGroupAddDTOList();
        if (!CollectionUtils.isEmpty(formGroupAddDTOList)) {
            formGroupService.batchSave(formGroupAddDTOList,tokenUser);
        }
        // 修改
        List<FormGroupUpdateDTO> formGroupUpdateDTOList = formGroupBatchDTO.getFormGroupUpdateDTOList();
        if (!CollectionUtils.isEmpty(formGroupUpdateDTOList)) {
            formGroupUpdateDTOList.parallelStream().forEach(
                    formGroupUpdateDTO -> {
                        formGroupService.update(formGroupUpdateDTO,tokenUser);
                    }
            );
        }
        // 删除
        List<Long> deleteFormGroupIdList = formGroupBatchDTO.getDeleteFormGroupIdList();
        if (!CollectionUtils.isEmpty(deleteFormGroupIdList)) {
            formGroupService.deleteByIds(tokenUser,false, deleteFormGroupIdList.toArray(new Long[0]));
        }
        return Result.success();
    }


    @Override
    @DeleteMapping(value = "/{formGroupId}")
    public Result<Integer> delete(@PathVariable Long formGroupId,
                                  @RequestParam(required = false) Boolean check) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除表单字段分组权限校验

        int count = formGroupService.deleteByIds(tokenUser, check, formGroupId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody Long[] formGroupIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除表单字段分组权限校验

        int count = formGroupService.deleteByIds(tokenUser, false, formGroupIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{formGroupId}")
    public Result<FormGroupVO> findById(@PathVariable Long formGroupId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看表单字段分组权限校验

        return Result.success(
            formGroupService.selectById(formGroupId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<FormGroupListVO>> listAll(@Valid FormGroupQuery formGroupQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看表单字段分组权限校验

        return Result.success(
            formGroupService.select(formGroupQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<FormGroupListVO>> page(@Valid FormGroupQuery formGroupQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
            formGroupService.selectPage(formGroupQuery, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/findForm/{formType}")
    public Result<List<FormGroupVO>> findForm(@PathVariable("formType") String formType,
                                              @RequestParam(value = "siteId", required = false) String siteId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验
        if (tokenUser == null) {
            if (StringUtils.isBlank(siteId)) {
                throw new ParamException("租户id不能为空");
            }
            //未登录状态查询供应商模板，根据url参数获取siteId
            tokenUser = new TokenUser();
            tokenUser.setSiteId(siteId);
            tokenUser.setUserId("h5");
        }
        return Result.success(
                formGroupService.findBySiteId(formType, tokenUser)
        );
    }

    @Override
    @GetMapping("/getHead")
    public Result<FormHeaderVO> getHead(HeaderFieldsQuery headerFieldsQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增自定义表格列的显示和隐藏权限校验
        headerFieldsQuery.setSubjectId(tokenUser.getSiteId());
        headerFieldsQuery.setCreateUserId(tokenUser.getUserId());
        return Result.success(
                formGroupService.getHead(headerFieldsQuery, tokenUser)
        );
    }

}

